package com.hqsj.thread;

import com.github.sd4324530.fastweixin.api.CustomAPI;
import com.github.sd4324530.fastweixin.api.MaterialAPI;
import com.github.sd4324530.fastweixin.api.UserAPI;
import com.github.sd4324530.fastweixin.api.entity.UserInfo;
import com.github.sd4324530.fastweixin.api.enums.MaterialType;
import com.github.sd4324530.fastweixin.api.response.GetUserInfoListResponse;
import com.github.sd4324530.fastweixin.api.response.GetUserInfoResponse;
import com.github.sd4324530.fastweixin.api.response.GetUsersResponse;
import com.github.sd4324530.fastweixin.message.Article;
import com.github.sd4324530.fastweixin.message.NewsMsg;
import com.github.sd4324530.fastweixin.message.TextMsg;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * Created by huangying on 2017/4/20.
 */
public class SendCustomMsgThread extends Thread {

    private String mediaId;

    private long beginTime;

    private long endTime;

    private UserAPI userAPI;

    private CustomAPI customAPI;

    private MaterialAPI materialAPI;

    public SendCustomMsgThread(String mediaId, long beginTime, long endTime, UserAPI userAPI, CustomAPI customAPI, MaterialAPI materialAPI) {
        this.mediaId = mediaId;
        this.beginTime = beginTime;
        this.endTime = endTime;
        this.userAPI = userAPI;
        this.customAPI = customAPI;
        this.materialAPI = materialAPI;
    }

    @Override
    public void run() {

        int sendCount = 0;
        Date sendStart = new Date();

        GetUsersResponse getUsersResponse = userAPI.getUsers("");
        long total = getUsersResponse.getTotal();
        String[] openids = getUsersResponse.getData().getOpenid();
        List<Article> articles = null;

        //最多获取10次，获取不到则放弃发送
        for (int i = 0; i < 10; i++) {
            articles = materialAPI.downloadMaterial(mediaId, MaterialType.NEWS).getNews();
            if (articles != null) {
                break;
            }
        }

        if (articles != null) {
            //循环获取openid，每次获取10000个
            int getOpenidCount = (int) Math.ceil(((double) total) / 10000);
            for (int i = 0; i < getOpenidCount; i++) {
                if (i > 0) {
                    getUsersResponse = userAPI.getUsers(getUsersResponse.getNextOpenid());
                    openids = getUsersResponse.getData().getOpenid();
                }

                //循环获取用户信息，每次获取100个
                List<UserInfo> list = new ArrayList<>();
                for (String openid: openids) {
                    list.add(new UserInfo(openid));
                }
                int getUserInfoCount = (int) Math.ceil(((double) list.size()) / 100);
                for (int j = 0; j < getUserInfoCount; j++) {
                    System.out.println(new SimpleDateFormat("HH:mm:ss").format(new Date()) + ":  i=" + i + ", j=" + j);
                    GetUserInfoListResponse getUserInfoListResponse;
                    if (j == getUserInfoCount - 1) {
                        getUserInfoListResponse = userAPI.getUserInfoList(list.subList(100 * j, list.size() - 1));
                    } else {
                        getUserInfoListResponse = userAPI.getUserInfoList(list.subList(100 * j, 100 * (j + 1)));
                    }
                    List<GetUserInfoResponse> getUserInfoResponses = getUserInfoListResponse.getUser_info_list();
                    //循环检测用户的关注时间是否在要发送消息的时间区间内
                    for (GetUserInfoResponse user: getUserInfoResponses) {

//                    if ("hy。".equals(user.getNickname()) || "优尼沃特_杨逢麦".equals(user.getNickname())) {
//                        System.out.println(user.getNickname() + "---" + user.getOpenid());
//                    }


                        if (user != null && user.getErrcode() == null && user.getSubscribe() == 1 && user.getSubscribeTime() > beginTime && user.getSubscribeTime() < endTime) {
                            customAPI.sendCustomMessage(user.getOpenid(), new NewsMsg(articles));
                            sendCount++;
                        }
                    }
                }

            }

            Date sendComplete = new Date();

            SimpleDateFormat sdf = new SimpleDateFormat("yyyy年MM月dd日 HH:mm:ss");
            StringBuffer msg = new StringBuffer();
            msg.append("群发客服消息完成。其中\n\n")
                    .append("头条标题：").append(articles.get(0).getTitle())
                    .append("\n时间段：")
                    .append(sdf.format(beginTime * 1000)).append("-").append(sdf.format(endTime * 1000))
                    .append("\n发送时间：").append(sdf.format(sendStart))
                    .append("\n发送完成时间：").append(sdf.format(sendComplete))
                    .append("\n发送人数：" + sendCount);

            System.out.println(msg.toString());

       //给杨逢麦发送客服消息通知结果（云逸未来）
            customAPI.sendCustomMessage("olwKpv1l4o41WxW9wSyTfilEzQlU", new TextMsg(msg.toString()));
            //给黄蓥发送客服消息通知结果（云逸未来）
            customAPI.sendCustomMessage("olwKpv0dNnSpyZ5_5SfXpZngbQGE", new TextMsg(msg.toString()));
        } else {
            //给黄蓥发送客服消息通知结果（云逸未来）
            customAPI.sendCustomMessage("olwKpv0dNnSpyZ5_5SfXpZngbQGE", new TextMsg("获取不到图文，发送图文客服消息失败"));
        }
    }
}
